//
//  CGQdetailViewController.swift
//  SheYangBigData
//
//  Created by 叁拾叁 on 2021/4/7.
//  Copyright © 2021 叁拾叁. All rights reserved.

import UIKit
import MJRefresh
import RxSwift
import RxDataSources
import Then



class CGQdetailViewController: SYBaseViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    var collectionView: UICollectionView!
    var header: CGQdetailHeadView?
    fileprivate var vm: SYCollectionViewPageViewModel<CGQyuweiModel>!
    var id: String!
    var  model: CGQshebeiinfoModel!
    var models: [NSDataListModel]!
    var bottom: CGQdetailBottomView!
    var isOnline: Int = 1
    
    var errorView = SYErrorView()

    
    init(id: String) {
        super.init(nibName: nil, bundle: nil)
        self.id = id
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewWillAppear(_ animated: Bool) {
        
        self.navigationController?.navigationBar.isHidden = false
        self.tabBarController?.tabBar.isHidden = true

    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = "设备详情"
        setCollectionView()
        //        setupViewModel()
        loadData()
        
        self.view.backgroundColor = Constant.bgViewColor
        
    }
    
    //    fileprivate func setupViewModel(deviceId: String) {
    //
    //
    //        vm = SYCollectionViewPageViewModel<CGQyuweiModel>()
    //        vm.collectionView = collectionView
    //        vm.emptyViewParams = ("", "", 40.0, 30.0)
    //        collectionView.vg_pageProtocol = vm
    ////        vm.getList(type: .yunweiList(page: 1, size:10), dispose: dispose)
    //        vm.getList(type: .kongzhiqiList(id: deviceId), dispose: self.dispose)
    //
    //        vm.getDataClosure = {[weak self] page in
    //            if let `self` = self {
    //                self.vm.getList(type: .kongzhiqiList(id: deviceId), dispose: self.dispose)
    //            }
    //        }
    //        vm.loadDataClosure = {[weak self] success in
    //            if let `self` = self {
    //                if success {
    //                    self.loadDataSuccessed()
    //                }
    //            }
    //        }
    //    }
    
    func loadDataSuccessed() {
        DispatchQueue.main.async {
            
            self.collectionView.reloadData()
        }
    }
    
    func loadData() {
        
        requestVM.baseRequest(disposeBag: dispose, type: .sheDetail(id: self.id), modelClass: SGBaseModel<CGQshebeiinfoModel>.self) {[weak self] (res) in
            
            if let `self` = self  {
                self.model = res.data ?? CGQshebeiinfoModel()
                
                self .controlList(isOnline: 1)
            }
            
        } Error: {
            
        }
    }
    
    func controlList(isOnline: Int) {
        
        self.isOnline = isOnline
        requestVM.baseRequest(disposeBag: dispose, type: .kongzhiqiList(id: self.model.deviceId ?? ""), modelClass: SGBaseNoPageListModel<NSDataListModel>.self) {[weak self] (res) in
            
            if let `self` = self  {
                
                self.models = res.data ?? []
                self.models = self.models.filter { $0.status == isOnline }
                self.loadDataSuccessed()
                
                if self.models.count == 0 {
                    self.errorView.isHidden = false
                }else{
                    self.errorView.isHidden = true
                }
                
            }
            
        } Error: {
            
        }
    }
    
    func setCollectionView() {
        
        
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        
        layout.itemSize = CGSize(width: 172.0.autoWidth(), height: 168.autoWidth())
        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 10
        layout.scrollDirection = .vertical
        collectionView = UICollectionView(frame: CGRect(x: 10, y: 0, width: SCREEN_WIDTH-20, height: SCREEN_HEIGHT - BOTTOM_SAFE_HEIGHT -  54.autoWidth()), collectionViewLayout: layout)
        collectionView.backgroundColor = .clear
        collectionView.showsHorizontalScrollIndicator = false
        
        
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(CGQdetailCell.self, forCellWithReuseIdentifier: NSStringFromClass(CGQdetailCell.self))
        collectionView.register(CGQdetailHeadView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "CGQdetailHeadView")
        self.view.addSubview(self.collectionView)
        //        collectionView.backgroundColor = Constant.bgViewColor
        
        bottom = CGQdetailBottomView(frame: CGRect(x: 0, y: SCREEN_HEIGHT - 54.autoWidth() - BOTTOM_SAFE_HEIGHT, width: SCREEN_WIDTH, height: 54.autoWidth() + BOTTOM_SAFE_HEIGHT))
        bottom.quanxuanBt.addAction {[weak self] in
            if let `self` = self {
                self.bottom.quanxuanBt.isSelected = !self.bottom.quanxuanBt.isSelected
                for (i,_) in self.models.enumerated() {
                    self.models[i].isSelect = self.bottom.quanxuanBt.isSelected
                }
                if self.bottom.quanxuanBt.isSelected  {
                    
                    self.bottom.imgView.image = UIImage(named: "detail_select")
                    self.bottom.tixianBt.backgroundColor = UIColor(hex: 0x0782FF)
                    
                }else{
                    self.bottom.imgView.image = UIImage(named: "detail_noselect")
                    self.bottom.tixianBt.backgroundColor = UIColor(hex: 0xC2C2C2)
                    
                    
                }
                self.collectionView.reloadData()
            }
        }
        
        
        bottom.tixianBt.addAction {[weak self] in
            if let `self` = self {
                let arr = self.models.filter { $0.isSelect == true }
                
                let ids: [String] = arr.map { $0.deviceId ?? "" }
                let idStr = ids.joined(separator: ",")
                
                var isOn = 0
                if self.bottom.tixianBt.titleLabel?.text  == "一键启用" {
                    isOn = 1
                    
                }
                
                self.requestVM.baseRequest(disposeBag: self.dispose, type: .yijianqidong(dic: ["parentDeviceId":self.model.deviceId ?? "","deviceIds":idStr,"enable":"\(isOn)"]), modelClass: SGBaseModel<CGQshebeiinfoModel>.self) {[weak self] (res) in
                    
                    if let `self` = self  {
                        
                        self .controlList(isOnline: abs(isOn-1))
                        
                    }
                    
                } Error: {
                    
                }
            }
        }
        
        self.view.addSubview(bottom)
        
        
        errorView.isHidden = true
        errorView.frame = CGRect(x: 0.0, y: 250.autoWidth(), width: SCREEN_WIDTH, height: self.view.frame.size.height-200.autoWidth())

        self.collectionView.addSubview(errorView)
    }
    //
    
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if (self.models != nil) {
            return self.models.count//self.vm.dataSource.count
            
        }
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: CGQdetailCell? = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(CGQdetailCell.self), for: indexPath) as? CGQdetailCell
        cell?.configure(model: self.models[indexPath.row])
        
        cell?.passParamsClosure = {[weak self]value in
            if let `self` = self {
                
                let v = value as! (String, NSControlParamsListModel)
                
                if v.0 == "bianji" {
                    
                    let vc  = CGQbianjichuanganqiViewController(id: self.model.deviceId ?? "", childDeviceId: self.models?[indexPath.row].deviceId ?? "")
                    self.sy_push(vc)
                    
                    
                }else{
                    
                    
                    let m: NSControlParamsListModel = v.1
                    
                    self.requestVM.baseRequest(disposeBag: self.dispose, type: .kongzhishebei(id: self.models?[indexPath.row].deviceId ?? "", value: m.value ?? ""), modelClass: SGBaseModel<CGQshebeiinfoModel>.self) {[weak self] (res) in
                        
                        if let `self` = self  {
                            
                            self .controlList(isOnline: self.isOnline)
                            
                            
                        }
                        
                    } Error: {
                        
                    }
                }
                
           
                
                
            }
            
        
        }
        return cell!
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        
        
        self.models[indexPath.row].isSelect = !self.models[indexPath.row].isSelect
        let arr = self.models.filter { $0.isSelect != true }
        if arr.count == 0 {
            
            self.bottom.imgView.image = UIImage(named: "detail_select")
            self.bottom.tixianBt.backgroundColor = UIColor(hex: 0xC2C2C2)
            
        } else {
            self.bottom.imgView.image = UIImage(named: "detail_noselect")
            self.bottom.tixianBt.backgroundColor = UIColor(hex: 0x0782FF)
            
            
        }
        self.collectionView.reloadData()
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "CGQdetailHeadView", for: indexPath) as? CGQdetailHeadView
        header?.passParamsClosure = {[weak self]value in
            if let `self` = self {
                
                if value as! Int == 1 {
                    self.header?.kai.isSelected = true
                    self.header?.guan.isSelected = false
                    self.bottom.tixianBt .setTitle("一键禁用", for: .normal)
                    
                    self.controlList(isOnline: 1)
                }else{
                    self.controlList(isOnline: 0)
                    self.bottom.tixianBt .setTitle("一键启用", for: .normal)
                    self.header?.kai.isSelected = false
                    self.header?.guan.isSelected = true
                    self.models = self.models.filter { $0.status == 0 }
                    self.loadDataSuccessed()
                    
                }
                
                
                
            }
        }
        header!.currentVC = self
        if self.model != nil {        
            header!.configure(model: self.model)
        }
        return header!
    }
    
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        
        return CGSize(width: SCREEN_WIDTH, height: 190.autoWidth() + 45.autoWidth())
        
    }
    
    func getcontrolValue()  {
        
        requestVM.baseRequest(disposeBag: dispose, type: .sheDetail(id: self.id), modelClass: SGBaseModel<CGQshebeiinfoModel>.self) {[weak self] (res) in
            
            if let `self` = self  {
                self.model = res.data ?? CGQshebeiinfoModel()
                
                self.requestVM.baseRequest(disposeBag: self.dispose, type: .kongzhiqiList(id: self.model.deviceId ?? ""), modelClass: SGBaseNoPageListModel<NSDataListModel>.self) {[weak self] (res) in
                    
                    if let `self` = self  {
                        self.models = res.data ?? []
                        let arr = self.models.filter { $0.isSelect != true }
                        if arr.count == 0
                        
                        {
                            self.bottom.imgView.image = UIImage(named: "detail_select")
                            self.bottom.tixianBt.backgroundColor = UIColor(hex: 0xC2C2C2)
                            
                        } else {
                            self.bottom.imgView.image = UIImage(named: "detail_noselect")
                            self.bottom.tixianBt.backgroundColor = UIColor(hex: 0x0782FF)
                            
                        }
                        
                        self.loadDataSuccessed()
                        
                        
                    }
                    
                } Error: {
                    
                }
            }
            
        } Error: {
            
        }
    }
}
